import { useState } from 'react'
import { Button, Modal, Select, theme, Tooltip } from 'antd'
import { DeleteOutlined, DownloadOutlined } from '@ant-design/icons'

import { addAGCellTexty } from '@oBiz/components/addTexty'
import { getFileTypeName } from '@oBiz/TrackOrder/utils'
import { TCellParams } from './interface'
import { useBoundStore } from './store'
import styles from './styles.module.less'

export const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'fileId': {
      return <ActionCell {...(p as TCellParams<'fileId'>)} />
    }
    case 'fileType': {
      return <FileTypeCell {...(p as TCellParams<'fileType'>)} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

function FileTypeCell({ value, data }: TCellParams<'fileType'>) {
  const changeFileType = useBoundStore(v => v.changeFileType)
  const [loading, setLoading] = useState(false)
  if (value == null || !data) return
  if (data.deleteFlag === 1) return getFileTypeName(value)
  return (
    <Select
      className={styles.editingEle}
      loading={loading}
      disabled={loading}
      options={getFileTypeName.valueList.map(v => ({ label: getFileTypeName(v), value: v }))}
      value={value}
      onChange={async v => {
        try {
          setLoading(true)
          await changeFileType(data.fileId, v)
        } finally {
          setLoading(false)
        }
      }}
    />
  )
}

function ActionCell({ value, data }: TCellParams<'fileId'>) {
  const { token } = theme.useToken()
  const delAttachment = useBoundStore(v => v.delAttachment)
  if (value == null || !data) return
  const { fileId, fileUrl, deleteFlag } = data
  if (deleteFlag === 1) return <del style={{ color: token.colorTextSecondary }}>已删除</del>
  return (
    <>
      <Tooltip title={!!fileUrl && '查看/下载'}>
        <Button
          style={{ visibility: !fileUrl ? 'hidden' : undefined }}
          type="link"
          icon={<DownloadOutlined />}
          disabled={!fileUrl}
          onClick={() => {
            if (fileUrl) open(fileUrl)
          }}
        />
      </Tooltip>
      <Tooltip title="删除">
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => {
            Modal.confirm({
              title: '确认要删除吗？',
              onOk: () => delAttachment(fileId),
            })
          }}
        />
      </Tooltip>
    </>
  )
}
